import {BaseInput} from './BaseInput';
import {AjaxMsg} from '../utils/AjaxMsg';

export class MobileNumInput extends BaseInput {
    constructor(form, dom){
        super(form, dom);

        this._label = '手机号';

        this.oldLength = 0;
        this.mobileNum = '';

        this.dom.on('input', this.onInput.bind(this));
    }

    onInput(){
        this.form.onChangeUser();
        this.form.sendSmsButton.onChangeMobileNum();

        var newValue = this.dom.val();
        var oldLength = this.oldLength;
        var newLength = newValue.length;
        this.oldLength = newLength;
        
        // 输入手机号
        if (newLength > oldLength) {
            if (newLength === 4 || newLength === 9) {
                this.dom.val(newValue.substring(0, newLength - 1) + ' ' + newValue.substr(newLength - 1, 1));
            } else {
                this.dom.val(newValue);
            }
        } else if (newValue.indexOf(' ') === -1 && newLength > 3) { // 粘贴数字位数至少四位，才处理格式
            if (newLength < 8) {
                this.dom.val(newValue.substr(0, 3) + ' ' + newValue.substr(3, newLength - 3));
            } else {
                this.dom.val(newValue.substr(0, 3) + ' ' + newValue.substr(3, 4) + ' ' + newValue.substr(7, newLength - 7));
            }
        } else if(newLength < oldLength){ //删除的操作
            if(newValue[newLength - 1] === ' '){
                this.dom.val(newValue.substr(0, newLength - 1));
            }
        } else {
            this.dom.val(newValue);
        }
        this.mobileNum = newValue.split(' ').join('');
        if(this.mobileNum.length >= 11){
            this.verifyMobileNum();
        }
    }

    validate(){
        if(super.validate()){
            if(!(/^1\d{10}$/.test(this.mobileNum))){
                this.setValidation(false, '手机号格式错误');
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    verifyMobileNum(){
        if(this.validate()){
            //请求api
            this.api.validateMobileNum({mobileNum: this.mobileNum}).then((msg) => {
                let ajaxMsg = new AjaxMsg(msg);
                ajaxMsg.showFocus(this.form);
                if(ajaxMsg.data.countdown){
                    this.form.sendSmsButton.startCountdown(ajaxMsg.data.countdown, ajaxMsg.data.time);
                }
                if(ajaxMsg.status === -1){ //禁止登录
                    this.form.disableLogin('请注册账号');
                    this.form.sendSmsButton.disable();
                } else {
                    
                }
            });
        }
    }

    getValue(){
        return this.mobileNum;
    }
}